import type { Formula } from '@/types/formula'
import fs from 'fs/promises'

let dir

let newestVer: string = "", newestVal = 0;

(await fs.readdir("extract/")).forEach(file => {
  // file name like 1.1.4.jar
  const ver = file.split(".").slice(0, 3).reduce((a, b) => a * 1 + parseInt(b) * 1, 0)
  if (ver > newestVal) {
    newestVal = ver
    newestVer = file.replace(".jar", "")
  }
});

try {
  dir = await fs.readdir(`.cache/extract/temp/${newestVer}/data/providencraft/recipes`, { recursive: true })
} catch (e) {
  console.log("读取配方出错！你可能需要下载最新版pdc并放在mods文件夹下，然后执行解包命令！")
  process.exit(1)
}

const FormulaSourceDataMap: string[] = []
const FormulaMap: Record<string, Formula[]> = {}

await Promise.all(dir.map(async (file) => {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const id = file.substring(0, file.length - 5) ?? []

  if (id) {
    try {
      FormulaMap[id] = []
      FormulaSourceDataMap.push(await fs.readFile(`.cache/extract/temp/${newestVer}/data/providencraft/recipes/${id}.json`, "utf-8"))
    } catch (e) {
      console.log(id, file);
    }
  }
}))

export function isRelatedFormula(id: string, data: unknown) {
  if (typeof data === "string") return data.includes(id)
}

Object.keys(FormulaMap).forEach((id) => {
  for (let i = 0; i < FormulaSourceDataMap.length; i++) {
    const data = JSON.parse(FormulaSourceDataMap[i])
    if (isRelatedFormula(id, JSON.stringify(data))) {
      FormulaMap[id].push(data)
    }
  }
})

/**
 * @param id 配方 id
 * @returns 
 */
export default function useRelatedFormula(id: string) {
  return FormulaMap[id]
}